package us.codecraft.netmagic.samples;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.downloader.HttpClientDownloader;
import us.codecraft.webmagic.selector.JsonPathSelector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author code4crafter@gmail.com <br>
 *         Date: 13-8-12 <br>
 *         Time: 下午2:31 <br>
 */
public class FedexSelector {

    public Map<String, String> process(String number) {
        HttpClientDownloader httpClientDownloader = new HttpClientDownloader();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("data", "{\"TrackPackagesRequest\":{\"appType\":\"wtrk\",\"uniqueKey\":\"\",\"processingParameters\":{\"anonymousTransaction\":true,\"clientId\":\"WTRK\",\"returnDetailedErrors\":true,\"returnLocalizedDateTime\":false},\"trackingInfoList\":[{\"trackNumberInfo\":{\"trackingNumber\":\"" + number + "\",\"trackingQualifier\":\"\",\"trackingCarrier\":\"\"}}]}}"));
        params.add(new BasicNameValuePair("action", "trackpackages"));
        params.add(new BasicNameValuePair("locale", "zh_CN"));
        params.add(new BasicNameValuePair("format", "json"));
        params.add(new BasicNameValuePair("version", "99"));
        String url = "https://www.fedex.com/trackingCal/track?" + URLEncodedUtils.format(params, "utf-8");
        //这个URL就是最终数据页面的地址，贴到浏览器就可以看效果，推荐用chrome+插件JSONView
        System.out.println("Downloading url "+url);
        //用到JsonPath做Json分析，https://code.google.com/p/json-path/
        Page page = httpClientDownloader.download(new Request(url), Site.me().setDomain("www.fedex.com").toTask());
        Map<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("Status",new JsonPathSelector("$..keyStatus").select(page.getHtml().toString()));
        resultMap.put("Date",new JsonPathSelector("$..shipDt").select(page.getHtml().toString()));
        return resultMap;
    }

    public static void main(String[] args) {
        FedexSelector fedexSelector = new FedexSelector();
        Map<String, String> result = fedexSelector.process("569763806180");
        System.out.println(result);
    }
}
